<template>
  <div>
    <el-container>
      <el-header>
        广告列表
      </el-header>
      <el-main>
        <el-card>
          <el-form :model="content" class="content-form">
            <el-form-item label="标题">
              <el-input v-model="content.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="类别">
              <el-select v-model="content.categoryId" placeholder="全部类别" style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option v-for="(item, index) in contentCategory" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button plain type="primary" @click="searchContent">
                搜索
              </el-button>
              <el-button plain @click="addContent">
                添加
              </el-button>
              <el-button plain @click="toggleSelection">
                删除
              </el-button>
            </el-form-item>
          </el-form>
          <el-table :data="tableData" class="content-list" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="广告 id" prop="id" />
            <el-table-column label="标题" prop="title" />
            <el-table-column label="路径" prop="url" />
            <el-table-column label="图片" prop="pic" />
            <el-table-column label="操作">
              <template slot="default" scope="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDetele(scope.$index, scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :background="background" :disabled="disabled" :page-sizes="[2, 3, 5, 7]" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>
        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
          <el-form :rules="rules" :model="contentInfo">
            <el-form-item :label-width="formLabelWidth" label="编号">
              <el-input v-model="contentInfo.id" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" prop="title" label="标题">
              <el-input v-model="contentInfo.title" autocomplete="off" />
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" prop="url" label="路径">
              <el-input v-model="contentInfo.url" autocomplete="off" />
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" prop="pic" label="图片">
              <el-upload class="upload-demo" action="" :http-request="uploadFile" :before-upload="beforeUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="类别">
              <el-select v-model="content.categoryId" placeholder="全部类别" style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option v-for="(item, index) in contentCategory" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="formSubmitHandler">
            确定
          </el-button>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import contentApi from '../http/httpContentRequest.js';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import axios from 'axios';
export default {
  data() {
    return {
      formLabelWidth: '100px',
      tableData: [],
      pageSize: 3,
      pageNum: 1,
      total: 20,
      background: false,
      disabled: false,
      content: {},
      contentCategory: [],
      multipleSelection: [],
      contentInfo: {},
      dialogFormVisible: false,
      dialogTitle: '添加广告',
      dialogImagePic: '',
      dialogVisible: false,
      rules: {
        title: [
          {
            required: true,
            message: '标题',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 16,
            message: '5-16 位非空字符',
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: 'url',
            trigger: 'blur'
          }
        ],
        categoryId: [
          {
            required: true,
            message: '请选择广告类别',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  mounted() {
    this.contentCategoryList();
  },
  methods: {
    handleCurrentChange(num) {
      this.pageNum = num;
      this.searchContent();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.searchContent();
    },
    searchContent() {
      const searchUrl = `/content/search/${this.pageNum}/${this.pageSize}`;
      contentApi.doPost(searchUrl, this.content).then(result => {
        this.tableData = result.data.pr.rows;
        this.total = result.data.pr.total;
      });
    },
    contentCategoryList() {
      contentApi.doGet("/contentCategory/list").then(result => {
        this.contentCategory = result.data.list;
      });
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.dialogTitle = '编辑广告';
      this.contentInfo.title = row.title;
      this.contentInfo.url = row.url;
      this.contentInfo.pic = row.pic;
      this.contentInfo.categoryId = row.categoryId;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDetele(index, row) {
      let ids = [];
      if (row) {  // 代表删除单个员工
        ids.push(row.id);
      } else {  // undefined 时表示批量删除的情况
        ids = this.multipleSelection.map(row => row.id).join(',');
      }
      contentApi.doDelete(`/content/delete/${ids}`).then(resp => {
        if (resp.code === 200) {
          this.$message({
            type: 'success',
            message: resp.message,
            onClose: () => {
              this.searchContent();
            }
          });
        } else {
          this.$message({
            type: 'error',
            message: resp.message
          });
        }
      });
    },
    addContent() {
      this.dialogFormVisible = true;
      this.dialogTitle = '添加广告';
      this.contentInfo = {};
    },
    toggleSelection() {
      // 可以根据需求添加具体逻辑，这里暂未实现具体功能
    },
    formSubmitHandler() {
      let result;
      ElMessageBox.confirm(`确认${this.dialogTitle}吗`).then(async () => {
        if (this.dialogTitle === '添加广告') {
          result = await contentApi.doPost("/content/add", this.contentInfo);
        }
        if (this.dialogTitle === '编辑广告') {
          this.contentInfo.pic = this.dialogImagePic;
          result = await contentApi.doPost("/content/update", this.contentInfo);
        }
        ElNotification({
          message: result.message,
          type: result.code === 200? 'success' : 'error'
        });
        this.searchContent();
      }).catch(() => {
        ElMessage.info('取消');
      });
      this.dialogFormVisible = false;
    },
    uploadFile({ file, onProgress, onSuccess, onError }) {
      const formData = new FormData();
      formData.append('file', file);
      axios.post('/hzit/content/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent: percentCompleted }, file);
        }
      }).then(response => {
        onSuccess(response.data);
        this.dialogImagePic = response.data.pic;
        this.dialogVisible = true;
      }).catch(error => {
        onError(error);
      });
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传文件只能是图片!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImagePic = file.pic;
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped>
.content-list {
  text-align: center;
}
.content-form {
  display: flex;
  text-align: center;
  justify-content: space-around;
}
</style>